package com.fingard.dsp.bank.directbank.ccblifeicbc02;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.dsp.bank.reqrespobj.single.detail.ReqPayRecDetail;
import com.fingard.net.WebRequest;
import com.fingard.text.StringHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextWriter;

public class CCBLifeICBC02Base extends DirectBase {
    protected String getCharset() {
        return getBankConfig().getCharset("GBK");
    }

    protected void writeCommonHeader(XmlTextWriter xmlWriter, CCBLifeICBC02Header tmpBankHeader) throws Exception {
        xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"GBK\"?>");
        xmlWriter.writeStartElement("CMS");
        xmlWriter.writeStartElement("eb");
        xmlWriter.writeStartElement("pub");
        xmlWriter.writeElementString("TransCode", tmpBankHeader.transCode);
        xmlWriter.writeElementString("CIS", bankFront.org);
        xmlWriter.writeElementString("BankCode", "102");
        xmlWriter.writeElementString("ID", bankFront.keyID);
        Date tmpDateNow = new Date();
//        xmlWriter.writeElementString("TranDate", Format.Date8Format.format(tmpDateNow));
        xmlWriter.writeElementString("TranDate", "20181101");
        xmlWriter.writeElementString("TranTime", Format.Time9Format.format(tmpDateNow));
        xmlWriter.writeElementString("fSeqno", tmpBankHeader.fSeqNo);
        xmlWriter.writeEndElement();
        xmlWriter.writeStartElement("in");
    }

    protected void writeBatCommonHeader(XmlTextWriter xmlWriter, CCBLifeICBC02Header tmpBankHeader) throws Exception {
        if (StringHelper.isNullOrEmpty(tmpBankHeader.transCode)) {
            throw new Exception("未赋值TransCode");
        }
        if (StringHelper.isNullOrEmpty(tmpBankHeader.fSeqNo)) {
            throw new Exception("未赋值fSeqno");
        }
        xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"" + getCharset() + "\"?>");
        xmlWriter.writeStartElement("CMS");
        xmlWriter.writeStartElement("eb");
        xmlWriter.writeStartElement("pub");
        xmlWriter.writeElementString("TransCode", tmpBankHeader.transCode);
        xmlWriter.writeElementString("CIS", bankFront.org);
        xmlWriter.writeElementString("BankCode", "102");
        xmlWriter.writeElementString("ID", bankFront.keyID);
        Date tmpDateNow = new Date();
        xmlWriter.writeElementString("TranDate", "20181101");
//        xmlWriter.writeElementString("TranDate", Format.Date8Format.format(tmpDateNow));
        xmlWriter.writeElementString("TranTime", Format.Time12Format.format(tmpDateNow));
        xmlWriter.writeElementString("fSeqno", tmpBankHeader.fSeqNo);
        xmlWriter.writeEndElement();
        xmlWriter.writeStartElement("in");
    }

    protected String[] sendToBank(String p_reqStr) throws Exception {
        String[] retStr = new String[]{"", ""};
        WriteBankLogLn("2.提交银行的地址：" + bankFront.serverURL);
        WriteBankLogStep2(p_reqStr);
        byte[] tmpToWriteBytes = p_reqStr.getBytes(getCharset());
        WebRequest tmpWebRequest = new WebRequest(bankFront.serverURL);
        tmpWebRequest.setConnectTimeout(600000);
        tmpWebRequest.setRequestProperty("Content-Type", "application/xml");
        tmpWebRequest.setRequestProperty("User-agent", "  Mozilla/5.0 (Windows NT 6.1; WOW64; rv:33.0) Gecko/20100101 Firefox/33.0");
        retStr = tmpWebRequest.upload(tmpToWriteBytes, getCharset());
        WriteBankLogStep3(retStr[1]);
        return retStr;
    }

    protected static boolean isActiveRetCode(String retCode) {
        if (retCode != null) {
            if (retCode.equals("") || retCode.equals("0") || retCode.equals("00000")) {
                return true;
            }
        }
        return false;
    }

    protected XElement convertPayRecDetailToBankXElement(ReqPayRecDetail p_atsDetail, int p_seqIndex, CCBLifeICBC02Header tmpBankHeader) throws Exception {
        XElement tmpXElement = new XElement("rd", "");
        tmpXElement.addChild(new XElement("iSeqno", String.valueOf(p_seqIndex)));
        tmpXElement.addChild(new XElement("ReimburseNo", ""));
        tmpXElement.addChild(new XElement("ReimburseNum", ""));
        tmpXElement.addChild(new XElement("StartDate", ""));
        tmpXElement.addChild(new XElement("StartTime", ""));
        //PayType 1：加急 2：普通
        if (!StringHelper.isNullOrEmpty(p_atsDetail.paySpd) && p_atsDetail.paySpd.equals("1")) {
            tmpXElement.addChild(new XElement("PayType", "1"));
        } else {
            tmpXElement.addChild(new XElement("PayType", "2"));
        }

        tmpXElement.addChild(new XElement("PayAccNo", p_atsDetail.payAct));
        tmpXElement.addChild(new XElement("PayAccNameCN", p_atsDetail.payName));
        tmpXElement.addChild(new XElement("PayAccNameEN", ""));
        tmpXElement.addChild(new XElement("RecAccNo", p_atsDetail.recAct));
        tmpXElement.addChild(new XElement("RecAccNameCN", p_atsDetail.recName));
        tmpXElement.addChild(new XElement("RecAccNameEN", ""));
        //1：系统内 2：系统外
        if (p_atsDetail.sameBnk.equals("1")) {
            tmpXElement.addChild(new XElement("SysIOFlg", "1"));
        } else {
            tmpXElement.addChild(new XElement("SysIOFlg", "2"));
        }
        //1：同城 2：异地
        if (p_atsDetail.sameCity.equals("1")) {
            tmpXElement.addChild(new XElement("IsSameCity", "1"));
        } else {
            tmpXElement.addChild(new XElement("IsSameCity", "2"));
        }
        if (tmpBankHeader.transCode.equals("PAYENT")) {
            //CMS/eb/in/rd/Prop	对公对私标志		0：对公账户		1：个人账户"
            //DSP针对对公对私标志的判断统一为，ATS发出的<IsPrivate>为2对公，其它则为对私
            if (p_atsDetail.isPrivate.equals("2")) {
                tmpXElement.addChild(new XElement("Prop", "0"));
            } else {
                tmpXElement.addChild(new XElement("Prop", "1"));
            }
        }
        String tmpRecICBCCode = "";
        tmpXElement.addChild(new XElement("RecICBCCode", tmpRecICBCCode));
        String tmpRecCityName = "";
        String tmpRecBankNo = "";
        String tmpRecBankName = p_atsDetail.recBankLocation;
        if (!p_atsDetail.sameBnk.equals("1")) {//跨行
            //RecCityName 收款方所在城市名称 跨行指令此项必输
            tmpRecCityName = p_atsDetail.recAreaName;
            if (StringHelper.hasAnyChar(p_atsDetail.cnapsCode)) {
                tmpRecBankNo = p_atsDetail.cnapsCode;
            }
            if (getBankConfig().getValueAsBool("setCnps999IfEmpty")) {//配置了为空则置12个9
                if (StringHelper.isNullOrEmpty(tmpRecBankNo)) {
                    tmpRecBankNo = "999999999999";
                }
            } else if (getBankConfig().getValueAsBool("setCnpsEmptyIf999")) {//配置了12个9置空
                if (StringHelper.hasAnyChar(tmpRecBankNo) && tmpRecBankNo.equals("999999999999")) {
                    tmpRecBankNo = "";
                }
            }
            if (StringHelper.hasAnyChar(p_atsDetail.cnapsName)) {
                tmpRecBankName = p_atsDetail.cnapsName;
            }
        }
        tmpXElement.addChild(new XElement("RecCityName", tmpRecCityName));
        tmpXElement.addChild(new XElement("RecBankNo", tmpRecBankNo));
        tmpXElement.addChild(new XElement("RecBankName", tmpRecBankName));
        tmpXElement.addChild(new XElement("CurrType", convertCurToBank(p_atsDetail.payCur)));
        tmpXElement.addChild(new XElement("PayAmt", StringHelper.amountMultiply100(p_atsDetail.payAmount)));
        tmpXElement.addChild(new XElement("UseCode", ""));
        String tmpUseCN = "";
        if (tmpBankHeader.transCode.equals("PAYPERCOL") || tmpBankHeader.transCode.equals("PAYPER")) {
            tmpUseCN = getICBCPayUse(p_atsDetail.useType);
            if (StringHelper.isNullOrEmpty(tmpUseCN)) {
                tmpUseCN = p_atsDetail.useType;
            }
        }
        if (StringHelper.isNullOrEmpty(tmpUseCN)) {
            tmpUseCN = p_atsDetail.purpose;
        }
        //UseCn长度不能超过10个字符
        tmpXElement.addChild(new XElement("UseCN", tmpUseCN.length()>10?tmpUseCN.substring(0,10):tmpUseCN));
        tmpXElement.addChild(new XElement("EnSummary", ""));
        tmpXElement.addChild(new XElement("PostScript", p_atsDetail.abstractATS));
        if (StringHelper.isNullOrEmpty(p_atsDetail.memo)) {
            tmpXElement.addChild(new XElement("Summary", p_atsDetail.purpose.length()>10?p_atsDetail.purpose.substring(0,10):p_atsDetail.purpose));
        } else {
            tmpXElement.addChild(new XElement("Summary", p_atsDetail.memo.length()>10?p_atsDetail.memo.substring(0,10):p_atsDetail.memo));
        }
        tmpXElement.addChild(new XElement("Ref", p_atsDetail.askNumber));
        tmpXElement.addChild(new XElement("Oref", p_atsDetail.askNumber));
        tmpXElement.addChild(new XElement("ERPSqn", p_atsDetail.askNumber));
        tmpXElement.addChild(new XElement("BusCode", ""));
        tmpXElement.addChild(new XElement("ERPcheckno", ""));
        tmpXElement.addChild(new XElement("CrvouhType", ""));
        tmpXElement.addChild(new XElement("CrvouhName", ""));
        tmpXElement.addChild(new XElement("CrvouhNo", ""));
        tmpXElement.addChild(new XElement("BankType", ""));
        tmpXElement.addChild(new XElement("FileNames", ""));
        tmpXElement.addChild(new XElement("Indexs", ""));
        tmpXElement.addChild(new XElement("PaySubNo", ""));
        tmpXElement.addChild(new XElement("RecSubNo", ""));
        tmpXElement.addChild(new XElement("MCardNo", ""));
        tmpXElement.addChild(new XElement("MCardName", ""));

        nodeAnalysis(p_atsDetail.srcXElement, tmpXElement, getCharset());

        return tmpXElement;
    }

    protected XElement convertRecDetailToBankXElement(ReqPayRecDetail p_atsDetail, int p_seqIndex, CCBLifeICBC02Header tmpBankHeader) throws Exception {
        XElement tmpXElement = new XElement("rd", "");

        tmpXElement.addChild(new XElement("iSeqno", String.valueOf(p_seqIndex)));
        tmpXElement.addChild(new XElement("PayAccNo", p_atsDetail.payAct));
        tmpXElement.addChild(new XElement("PayAccNameCN", p_atsDetail.payName));
        tmpXElement.addChild(new XElement("PayAccNameEN", ""));
        String payBranch = p_atsDetail.payBankName;
        if (StringHelper.isNullOrEmpty(payBranch)) {
            payBranch = "中国工商银行";
        }
        tmpXElement.addChild(new XElement("PayBranch", payBranch));
        if ("PERDISCOL".equals(tmpBankHeader.transCode) || "PERDIS".equals(tmpBankHeader.transCode)) {
            if (StringHelper.hasAnyChar(p_atsDetail.authCode)) {
                tmpXElement.addChild(new XElement("Portno", p_atsDetail.authCode));
            } else {
                int intLastNum = 30 - p_atsDetail.payAct.length();
                if (p_atsDetail.payName.length() > intLastNum) {
                    tmpXElement.addChild(new XElement("Portno", p_atsDetail.payAct + p_atsDetail.payName.substring(0, intLastNum)));
                } else {
                	tmpXElement.addChild(new XElement("Portno", getBankConfig().getValueAsString("portno")));
                }
            }
            if (StringHelper.hasAnyChar(p_atsDetail.authAgNum)) {
                tmpXElement.addChild(new XElement("ContractNo", p_atsDetail.authAgNum));
            } else {
                tmpXElement.addChild(new XElement("ContractNo", getBankConfig().getValueAsString("contractNo")));
            }
        }
        tmpXElement.addChild(new XElement("CurrType", convertCurToBank(p_atsDetail.payCur)));
        tmpXElement.addChild(new XElement("PayAmt", StringHelper.amountMultiply100(p_atsDetail.payAmount)));

        String tmpUseCN = "";
        if ("PERDISCOL".equals(tmpBankHeader.transCode) || "PERDIS".equals(tmpBankHeader.transCode) || "ENTDIS".equals(tmpBankHeader.transCode)) {
            tmpUseCN = getICBCPayUse(p_atsDetail.useType);
            if (StringHelper.isNullOrEmpty(tmpUseCN)) {
                tmpUseCN = p_atsDetail.useType;
            }
            if (StringHelper.isNullOrEmpty(tmpUseCN)) {
                tmpUseCN = p_atsDetail.purpose;
            }
            if (StringHelper.isNullOrEmpty(tmpUseCN)) {
                tmpUseCN = p_atsDetail.abstractATS;
            }
            tmpXElement.addChild(new XElement("UseCode", ""));
            tmpXElement.addChild(new XElement("UseCN", tmpUseCN));
        }
        tmpXElement.addChild(new XElement("EnSummary", ""));
        tmpXElement.addChild(new XElement("PostScript", p_atsDetail.abstractATS));
        if (StringHelper.isNullOrEmpty(p_atsDetail.memo)) {
            tmpXElement.addChild(new XElement("Summary", p_atsDetail.purpose));
        } else {
            tmpXElement.addChild(new XElement("Summary", p_atsDetail.memo));
        }
        tmpXElement.addChild(new XElement("Ref", "PERDIS".equals(tmpBankHeader.transCode) ? "" : p_atsDetail.askNumber));
        tmpXElement.addChild(new XElement("Oref", "PERDIS".equals(tmpBankHeader.transCode) ? "" : p_atsDetail.askNumber));
        tmpXElement.addChild(new XElement("ERPSqn", p_atsDetail.askNumber));
        tmpXElement.addChild(new XElement("BusCode", ""));
        tmpXElement.addChild(new XElement("ERPcheckno", ""));
        tmpXElement.addChild(new XElement("CrvouhType", ""));
        tmpXElement.addChild(new XElement("CrvouhName", ""));
        tmpXElement.addChild(new XElement("CrvouhNo", ""));
        tmpXElement.addChild(new XElement("ReqReserved3", ""));
        tmpXElement.addChild(new XElement("ReqReserved4", ""));

        nodeAnalysis(p_atsDetail.srcXElement, tmpXElement, getCharset());

        return tmpXElement;
    }

    public String getICBCPayUse(String p_payUse) throws Exception {
        String tmpValue = getBankConfig().getMapValueByKey("payUseMapping", p_payUse);
        if (StringHelper.isNullOrEmpty(p_payUse)) {
            if (StringHelper.isNullOrEmpty(tmpValue)) {
                return p_payUse;
            } else {
                return tmpValue;
            }
        } else {
            return tmpValue;
        }
    }

    //根据年月求每个月的月末日期
    public static String dateConvert(Date date) throws ParseException {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        int days = c.getActualMaximum(Calendar.DAY_OF_MONTH);
        c.add(Calendar.DAY_OF_MONTH, days - 1);
        Date date2 = c.getTime();
        String monthend = new SimpleDateFormat("yyyyMMdd").format(date2);
        return monthend;
    }
}
